/*********************************************************************************
 *      Copyright:  (C)Guo Zixuan
 *                  All rights reserved.
 *
 *       Filename:  server_sql.c
 *    Description:  This file 
 *                 
 *        Version:  1.0.0(09/04/25)
 *         Author:  Guo Zixuan <guozixuan@gmail.com>
 *      ChangeLog:  1, Release initial version on "09/04/25 15:32:21"
 *                 
 ********************************************************************************/
#include "server_sql.h"

int sqlite_init(sqlite3 **db, const char *db_name)
{
	int rc = sqlite3_open(db_name, db);

	if (rc != SQLITE_OK)
	{
		log_error("Cannot open database: %s\n", sqlite3_errmsg(*db));
		return -1;
	}
	log_info("Database opened successfully.\n");
	return 0;
}

int sqlite_create_table(sqlite3 *db) 
{
	char *sql = "CREATE TABLE IF NOT EXISTS servertable ("
				"id INTEGER PRIMARY KEY AUTOINCREMENT, "
				"data TEXT NOT NULL); ";
	char *err_msg = NULL;
	int rc = sqlite3_exec(db, sql, NULL, NULL, &err_msg);
	
	if (rc != SQLITE_OK)
	{
		log_error("SQL error: %s\n", err_msg);
		sqlite3_free(err_msg);
		return -1;
	}
	log_info("Table created successfully.\n");
	return 0;
}

int sqlite_insert_data(sqlite3 *db, char *buf) 
{
	char sql[512];
	snprintf(sql, sizeof(sql), "INSERT INTO servertable (data) VALUES ('%s');", buf);

	char *err_msg = NULL;
	int rc = sqlite3_exec(db, sql, NULL, NULL, &err_msg);
	if (rc != SQLITE_OK)
	{
		log_error("Insert failed: %s\n", err_msg);
		sqlite3_free(err_msg);
		return -1;
	}

	log_info("Data inserted successfully.\n");
	return 0;
}

int sqlite_close_db(sqlite3 *db)
{
	int rc = sqlite3_close(db);
	if (rc != SQLITE_OK)
	{
		log_error("Failed to close database: %s\n", sqlite3_errmsg(db));
		return -1;
	}
	log_info("Database closed successfully.\n");
	return 0;
}

